package com.yuerenjf.yuerenjinfu.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.PtrHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.qiniu.android.utils.StringUtils;
import com.special.ResideMenu.ResideMenu;
import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.activity.MainActivity;
import com.yuerenjf.yuerenjinfu.activity.WebActivity;
import com.yuerenjf.yuerenjinfu.adapter.AdapterHomeRecyler;
import com.yuerenjf.yuerenjinfu.adapter.AdapterHomeRecyler2;
import com.yuerenjf.yuerenjinfu.bean.MainDataBean;
import com.yuerenjf.yuerenjinfu.customview.AutoVerticalScrollTextView;
import com.yuerenjf.yuerenjinfu.customview.MyPtrClassicFrameLayout;
import com.yuerenjf.yuerenjinfu.http.Constants;
import com.yuerenjf.yuerenjinfu.http.Xutils;
import com.yuerenjf.yuerenjinfu.utils.MyDisplayImageOptions;
import com.yuerenjf.yuerenjinfu.widget.MyConvenientBanner;

import org.xutils.common.util.LogUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.iwgang.countdownview.CountdownView;


/**
 * Created by Administrator on 2016/6/13.
 */
public class FragmentHome extends BaseFragment implements View.OnClickListener {

    private static final int MSG_UPDATE_INFO = 0x110;
    private HandlerThread mCheckMsgThread;
    private MyPtrClassicFrameLayout mPtrClassicFrameLayout;
    private RecyclerView home_recyclerview;
    private LinearLayoutManager mLinearLayoutManager;
    ConvenientBanner convenientBanner;
    private AdapterHomeRecyler2 mAdapter;





    Handler mCheckMsgHandler;
    private Handler mHandler = new Handler();
    private Handler mHandler2 = new Handler();
    private int number;

    CountdownView countdownView;
    TextView mHome_top_start_tv;
    private long remainTime;
    private long pauseTime;
    Timer mTimer;
    MainDataBean.DataBean.CurBorrowBean countBean;

    @Override
    public void prepareData() {

    }
    private View topView;
    AutoVerticalScrollTextView mScrollNewsTextView;
    private boolean isUpdateInfo;

    @Override
    public View prepareView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_home, null);
        mPtrClassicFrameLayout = (MyPtrClassicFrameLayout) view.findViewById(R.id.MyPtrClassicFrameLayout);
        home_recyclerview = (RecyclerView) view.findViewById(R.id.home_recyclerview);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LogUtil.i("onActivityCreated");
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.setmTitleTextView("首页");
        mainActivity.setLogoImageShow(true);


//        getDataForRemote();
    }

    private void setHeader(final List<MainDataBean.DataBean.HomeBannerBean> bannerBeanList, final MainDataBean.DataBean.CurBorrowBean mCurBorrowBean,final List<MainDataBean.DataBean.TenderListsBean> beanList) {
        View topView = LayoutInflater.from(getActivity()).inflate(R.layout.home_top2, home_recyclerview, false);


        MyConvenientBanner convenientBanner = (MyConvenientBanner) topView.findViewById(R.id.convenientBanner);
        MainActivity parentActivity = (MainActivity) getActivity();
        ResideMenu resideMenu = parentActivity.getResideMenu();
        resideMenu.addIgnoredView(convenientBanner);

        convenientBanner.startTurning(4000);
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, bannerBeanList).setPageIndicator(new int[]{R.drawable.home_banner_dot, R.drawable.home_banner_cur}).setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
        convenientBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                WebActivity.launchActivity(getActivity(), bannerBeanList.get(position).getUrl());
            }
        });


        mPtrClassicFrameLayout.setViewPager(convenientBanner);

        mScrollNewsTextView = (AutoVerticalScrollTextView) topView.findViewById(R.id.find_news_item_title_text);
        mScrollNewsTextView.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                TextView textView = new TextView(getActivity());
                textView.setGravity(Gravity.CENTER);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                textView.setSingleLine(true);
                textView.setEllipsize(TextUtils.TruncateAt.END);
                textView.setTextColor(Color.parseColor("#999999"));
                FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                lp.gravity = Gravity.CENTER_VERTICAL;
                textView.setLayoutParams(lp);

                return textView;
            }
        });
        mScrollNewsTextView.setText(beanList.get(0).toString());
        mCheckMsgThread = new HandlerThread("check-message-coming");
        mCheckMsgThread.start();
        mCheckMsgHandler = new Handler(mCheckMsgThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (isUpdateInfo) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mScrollNewsTextView.next();
                            number++;
                            if (number == beanList.size()) {
                                number = 0;
                            }
                            mScrollNewsTextView.setText(beanList.get(number % beanList.size()).toString());
                        }
                    });
                    if (!mCheckMsgHandler.hasMessages(MSG_UPDATE_INFO)) {
                        mCheckMsgHandler.sendEmptyMessageDelayed(MSG_UPDATE_INFO, 2000);
                    }
                }
            }
        };
        mCheckMsgHandler.sendEmptyMessage(MSG_UPDATE_INFO);

















        LinearLayout mHome_top_layout = (LinearLayout) topView.findViewById(R.id.home_top_new_layout);

        if (null == mCurBorrowBean || null == mCurBorrowBean.getBorrow_id()) {
            mHome_top_layout.setVisibility(View.GONE);
        } else {
            TextView mHome_top_title_text = (TextView) topView.findViewById(R.id.home_top_title_text);

//            TextView mHome_top_shouyi_text= (TextView) topView.findViewById(R.id.home_top_shouyilv_tv);
//            mHome_top_shouyi_text.setText("13");
//
//            TextView mHome_top_shouyi_qixian_text= (TextView) topView.findViewById(R.id.home_top_shouyi_qixian_tv);
//            mHome_top_shouyi_qixian_text.setText("2个月");



            TextView mHome_top_startPoint_text = (TextView) topView.findViewById(R.id.home_top_start_point_tv);
            mHome_top_start_tv = (TextView) topView.findViewById(R.id.home_top_start_tv);
            ImageView home_top_btn_status_image = (ImageView) topView.findViewById(R.id.home_top_btn_image);
            countdownView = (CountdownView) topView.findViewById(R.id.countDownView);
            mHome_top_layout.setVisibility(View.VISIBLE);
            mHome_top_title_text.setText(mCurBorrowBean.getBorrow_title());
            mHome_top_startPoint_text.setText(mCurBorrowBean.getLowest_account() + "元起投");
            mHome_top_start_tv.setVisibility(View.GONE);
            countdownView.setVisibility(View.VISIBLE);
            if (mCurBorrowBean.isIs_full()) {
                mHome_top_start_tv.setText("已售空");
                home_top_btn_status_image.setImageResource(R.drawable.icon_home_top_gray);
                mHome_top_start_tv.setVisibility(View.VISIBLE);
                countdownView.setVisibility(View.GONE);
            } else {
                home_top_btn_status_image.setImageResource(R.drawable.icon_home_start_top);
                if (mCurBorrowBean.is_show_time()) {
                    mHome_top_start_tv.setText("马上开抢");
                    mHome_top_start_tv.setVisibility(View.VISIBLE);
                    countdownView.setVisibility(View.GONE);
                } else {
                    long duration = mCurBorrowBean.getTime_now() - System.currentTimeMillis() / 1000;//服务器与本地相差秒数
                    Log.i("restTime","top:"+duration);
                    mCurBorrowBean.setCountDown(duration);
                    long restTime = Long.valueOf(mCurBorrowBean.getTime_start()) - mCurBorrowBean.getTime_now();
                    Log.i("restTime:",restTime+"--");
                    countdownView.setmRemainTime(restTime*1000);
                     mTimer = new Timer();
                    mTimer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            mHandler2.post(mRefreshTimeRunnable);
                        }
                    }, 0, 1000);


                }
            }

            home_top_btn_status_image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    WebActivity.launchActivity(getActivity(), mCurBorrowBean.getBorrow_url());
//                    if(mHome_top_start_tv.getText().toString().equals("立即出借")){
//
//                    }
                }
            });

        }
        mAdapter.setHeaderView(topView);
    }

    public class NetworkImageHolderView implements Holder<MainDataBean.DataBean.HomeBannerBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, MainDataBean.DataBean.HomeBannerBean data) {
            String pic = data.getPic();
            if (!StringUtils.isNullOrEmpty(pic)) {
                if (pic.contains("http:") || pic.contains("https:")) {
                    ImageLoader.getInstance().displayImage(pic, imageView, MyDisplayImageOptions.getInstance(R.drawable.icon_banner_default));
                } else {
                    ImageLoader.getInstance().displayImage("http:" + pic, imageView, MyDisplayImageOptions.getInstance(R.drawable.icon_banner_default));
                }
            }


        }
    }

    @Override
    public void onClick(View view) {
    }


    @Override
    public void onloadData(View view) {


        mPtrClassicFrameLayout.postDelayed(new Runnable() {

            @Override
            public void run() {
                mLinearLayoutManager = new LinearLayoutManager(getActivity());
                home_recyclerview.setLayoutManager(mLinearLayoutManager);
                mPtrClassicFrameLayout.autoRefresh(true);
            }
        }, 150);
        mPtrClassicFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                if(home_recyclerview==null){
                   return false;
                }
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, home_recyclerview, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mPtrClassicFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getDataForRemote();
                    }
                }, 100);
            }
        });
    }

    @Override
    public void adapterScreen() {

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        isUpdateInfo = true;
        if (mCheckMsgHandler != null) {
            if (!mCheckMsgHandler.hasMessages(MSG_UPDATE_INFO)) {
                mCheckMsgHandler.sendEmptyMessage(MSG_UPDATE_INFO);
            }
        }
        if (convenientBanner != null) {
            convenientBanner.startTurning(5000);
        }
        if (null != mAdapter) {
            mAdapter.startRefreshTime();
        }

//        LogUtil.i("OnResume");
//        if(null!=countdownView){
//            countdownView.restart();
//            countdownView.updateShow(countdownView.getRemainTime());
//        }

    }

    @Override
    public void onPause() {
        super.onPause();
        if (convenientBanner != null) {
            convenientBanner.stopTurning();
        }
        if (null != mAdapter) {
            mAdapter.cancelRefreshTime();
        }


        LogUtil.i("OnPause");
        if (null != countdownView) {
//            pauseTime=System.currentTimeMillis();
            long remainTime = countdownView.getRemainTime();
            LogUtil.i(remainTime + "-------------");
            countdownView.pause();

        }
    }

    @Override
    public void onStop() {
        super.onStop();
        isUpdateInfo = false;
        if (mCheckMsgHandler != null) {
            if (mCheckMsgHandler.hasMessages(MSG_UPDATE_INFO)) {
                mCheckMsgHandler.removeMessages(MSG_UPDATE_INFO);
            }
        }


    }

    private void initRecyclerView(final List<MainDataBean.DataBean.CurBorrowsBean> homeList) {
        mAdapter = new AdapterHomeRecyler2(getActivity());
        home_recyclerview.setAdapter(mAdapter);
        mAdapter.addDatas(homeList);
        mAdapter.setOnItemClickListener(new AdapterHomeRecyler2.OnItemClickListener() {
            @Override
            public void onItemClick(int position, MainDataBean.DataBean.CurBorrowsBean data) {

                WebActivity.launchActivity(getActivity(), homeList.get(position - 1).getBorrow_url());
            }
        });
        mPtrClassicFrameLayout.disableWhenHorizontalMove(true);


    }

    private void getDataForRemote() {

        Map<String, String> map = new HashMap<>();
        Xutils.getInstance().get(getActivity(), Constants.URL_HOME, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                Log.i("result",result);
                MainDataBean mainDataBean = gson.fromJson(result, MainDataBean.class);
                MainDataBean.DataBean dataBean = mainDataBean.getData();
                if (dataBean == null) {
                    return;
                }

                initRecyclerView(dataBean.getCur_borrows());
                countBean = dataBean.getCur_borrow();
                setHeader(dataBean.getHome_banner(), dataBean.getCur_borrow(),dataBean.getTender_lists());

                setFootView();
            }

            @Override
            public void onFailer(int status, String result) {
                LogUtil.i("onFailer");
            }

            @Override
            public void onFinish() {
                mPtrClassicFrameLayout.refreshComplete();
            }
        });


    }


    private void setFootView() {
        View footView = LayoutInflater.from(getActivity()).inflate(R.layout.home_recyclervie_footview, home_recyclerview, false);



        mAdapter.setFootView(footView);


    }


    private Runnable mRefreshTimeRunnable = new Runnable() {
        @Override
        public void run() {

            long currentTime = System.currentTimeMillis() / 1000;
            Log.i("restTime", "currentTime" + currentTime + "-----");
            long a = countdownView.getRemainTime() / 1000;
            if (a <= 0) {
                // 倒计时结束
//                        curMyViewHolder.mItem_lend_youxuan_sell_status_text.setBackgroundResource(R.drawable.icon_home_btn_bg);
//                        curMyViewHolder.setSellStatusText("立即出借");
//                        curMyViewHolder.mCvCountdownView.setVisibility(View.GONE);
                countdownView.stop();
                mHome_top_start_tv.setVisibility(View.VISIBLE);
                mHome_top_start_tv.setText("马上开抢");
                countdownView.setVisibility(View.GONE);
                if(mTimer!=null){
                    mTimer.cancel();
                }
                mHandler2.removeCallbacks(mRefreshTimeRunnable);
//                        curMyViewHolder.getmItemInfo().setIs_show_time(true);
//                        notifyDataSetChanged();

            } else {
                Log.i("restTime", "Top倒计时开始");
                refreshTime();
            }

        }
    };
    public void refreshTime() {
        if (null == countBean ||countdownView.getRemainTime() <=0)
            return;
//            mCvCountdownView.updateShow((Long.valueOf(mItemInfo.getTime_start()) - System.currentTimeMillis() / 1000 + mItemInfo.getCountdown()) * 1000);
        countdownView.updateShow((Long.valueOf(countBean.getTime_start()) - System.currentTimeMillis() / 1000 + countBean.getCountDown()) * 1000);
    }


}
